package com.book.model.service.impl;

import com.book.model.criteria.Criteria;
import com.book.model.criteria.Restrictions;
import com.book.model.entity.*;
import com.book.model.repository.*;
import com.book.model.service.TmpCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service("TmpCacheService")
public class TmpCacheServiceImpl implements TmpCacheService {

    @Autowired
    TmpCacheRepository tmpCacheRepository;

    @Override
    public String get(String key) {
        TmpCache tmpCache = tmpCacheRepository.findOneByCKey(key);
        if(tmpCache == null){
            return null;
        }else if(tmpCache.getEndTime() < System.currentTimeMillis()){
            tmpCacheRepository.delete(tmpCache);
            return null;
        }
        return tmpCache.getCValue();
    }

    @Override
    public void set(String key, String value,long expireIn) {
        TmpCache tmpCache = tmpCacheRepository.findOneByCKey(key);
        if(tmpCache == null) {
            tmpCache = new TmpCache();
            tmpCache.setCKey(key);
        }
        tmpCache.setCValue(value);
        tmpCache.setEndTime(System.currentTimeMillis()  + expireIn * 1000);
        tmpCacheRepository.save(tmpCache);
    }

    @Override
    public void delayedExpireTime(String key, long expireIn) {
        TmpCache tmpCache = tmpCacheRepository.findOneByCKey(key);
        if(tmpCache != null){
            tmpCache.setEndTime(tmpCache.getEndTime() + expireIn);
            tmpCacheRepository.save(tmpCache);
        }
    }

    @Override
    public void delete(String key) {
        TmpCache tmpCache = tmpCacheRepository.findOneByCKey(key);
        if(tmpCache != null){
            tmpCacheRepository.delete(tmpCache);
        }
    }

    @Override
    public void clearExpireOut() {
        Criteria<TmpCache> cacheCriteria = new Criteria<>();
        cacheCriteria.add(Restrictions.lt("endTime",System.currentTimeMillis()));
        List<TmpCache> tmpCaches = tmpCacheRepository.findAll(cacheCriteria);
        tmpCacheRepository.deleteAll(tmpCaches);
    }
}
